package edu.ustb.efws.pipeline.collect;

import edu.ustb.efws.EfwsProperties;
import edu.ustb.efws.base.domain.Position;
import edu.ustb.efws.base.domain.User;
import edu.ustb.efws.base.service.PositionService;
import edu.ustb.efws.base.service.SmsService;
import edu.ustb.efws.base.service.UserService;
import edu.ustb.efws.pipeline.collect.handler.WarSmsCache;
import edu.ustb.efws.utils.SafeMath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 短信发送引擎
 *
 * @author TS Group
 */
@Component
public class SmsLauncher implements DisposableBean {
    private static final Logger LOGGER = LoggerFactory.getLogger(SmsLauncher.class);
    private static final AtomicBoolean RUNNING = new AtomicBoolean(false);

    private final EfwsProperties properties;
    private final UserService userService;
    private final SmsService smsService;
    private final PositionService positionService;
    private final ScheduledExecutorService executorService;

    @Autowired
    public SmsLauncher(EfwsProperties properties, UserService userService, SmsService smsService, PositionService positionService) {
        this.properties = properties;
        this.userService = userService;
        this.smsService = smsService;
        this.positionService = positionService;
        this.executorService = Executors.newSingleThreadScheduledExecutor();
    }

    //开始数据采集
    public void start(){
        if(properties.isEnableCollect() && RUNNING.compareAndSet(false, true)){
            executorService.scheduleAtFixedRate(this::sendWaringSms,30,30, TimeUnit.SECONDS);
            LOGGER.info("Sms launcher start ...");
        }
    }

    private void sendWaringSms(){
        try{
            WarSmsCache cache = WarSmsCache.INSTANCE;
            Optional<WarSmsCache.WaringSmsTime> warOpt = cache.getWaring(
                    (int)Duration.ofSeconds(properties.getSmsWarIntervalSecs()).toMillis(),
                    (int)Duration.ofMinutes(2).toMillis());

            if(!warOpt.isPresent()){
                return ;
            }

            List<User> users = userService.querySms();
            Position position = positionService.get(warOpt.get().positionId);
            String grade = SafeMath.riskGrade(warOpt.get().score);
            for(User user: users){
                smsService.send(user.getTel(), position.getRiskArea(), position.getRiskPosition(), grade);
            }
            cache.updateSmsTime();
        }catch (Exception e){
            LOGGER.error("Sms launcher send warring fail error={}", e.getMessage());
        }
    }

    @Override
    public void destroy() throws Exception {
        if(RUNNING.compareAndSet(true, false)){
            executorService.shutdown();
            LOGGER.debug("Sms launcher shutdown ...");
        }
    }
}
